package com.kobeliu.controller;

//import com.kobeliu.api.config.ZkConnecter;
//import com.kobeliu.api.config.ZkLock;
import com.kobeliu.base.BaseInfoProperties;
import com.kobeliu.pojo.SysParams;
import com.kobeliu.pojo.vo.SysParamsVO;
import com.kobeliu.result.GraceJSONResult;
import com.kobeliu.result.ResponseStatusEnum;
import com.kobeliu.service.SysParamService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
//import org.apache.curator.framework.CuratorFramework;
//import org.apache.curator.framework.recipes.locks.InterProcessLock;
//import org.apache.curator.framework.recipes.locks.InterProcessMutex;
//import org.apache.zookeeper.KeeperException;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("sys")
@Slf4j
public class SysParamController extends BaseInfoProperties {

    @Autowired
    private SysParamService sysParamService;

    @Autowired
    private RedissonClient redissonClient;

//    @Autowired
//    private ZkConnecter zkConnecter;

//    @Autowired
//    @Qualifier("curatorClient")
//    private CuratorFramework curatorClient;

    @PostMapping("modifyMaxResumeRefreshCounts")
    public GraceJSONResult modifyMaxResumeRefreshCounts(Integer maxCounts,Integer version) throws Exception {

        if(maxCounts ==null || maxCounts<1){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.SYSTEM_PARAMS_SETTINGS_ERROR);
        }

        //使用zk 分布式锁进行version控制
        //创建锁
//        ZkLock lock = zkConnecter.getLock("imooc-lock");
        //获取锁
//        lock.get();

        //可重入分布式锁
//        InterProcessMutex processMutex = new InterProcessMutex(
//                curatorClient
//                ,"/mutex-locks"
//        );
//
//        try{
//            //获取锁
//            processMutex.acquire();

        RLock lock = redissonClient.getLock(version + "");

        lock.lock();
        sysParamService.modifyMaxResumeRefreshCounts(maxCounts,version);
        lock.unlock();
//        }finally {
//            processMutex.release();
//        }

        //释放锁
//        lock.release();

        return GraceJSONResult.ok(0);
    }

    @PostMapping("params")
    public GraceJSONResult params(){
        SysParamsVO vo = sysParamService.params();
        return GraceJSONResult.ok(vo);
    }

    @PostMapping("paramsByFeign")
    public Integer paramsByFeign(){

        return sysParamService.params().getMaxResumeRefreshCounts();
    }
}
